﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace WoltersKluwer.SPChainGang.Core.Util
{
    public static class FTPHelper
    {
        private static int BUFF_SIZE = 1024;

        public static string UploadToFtp(string ftpfilepath, string inputfilepath, string ftpHost, string userId, string pass)
        {
            return UploadToFtp(ftpfilepath, inputfilepath, ftpHost, userId, pass, true);
        }
        public static string UploadToFtp(string ftpfilepath, string inputfilepath, string ftpHost, string userId, string pass, bool directoryExist)
        {
            string result = string.Empty;
            string ftpfullpath = "ftp://" + ftpHost + ftpfilepath;
            FtpWebRequest ftp;
            if (!directoryExist)
            {
                ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath.Replace(Path.GetFileName(ftpfullpath), string.Empty));
                ftp.Credentials = new NetworkCredential(userId, pass);
                ftp.KeepAlive = true;
                ftp.UseBinary = true;
                ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
                using (var resp = (FtpWebResponse)ftp.GetResponse())
                {
                }
            }
            
            ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
            ftp.KeepAlive = true;
            ftp.UseBinary = true;
            ftp.Credentials = new NetworkCredential(userId, pass);
            ftp.Method = WebRequestMethods.Ftp.UploadFile;
            using (FileStream fs = File.OpenRead(inputfilepath))
            {
                using (Stream ftpstream = ftp.GetRequestStream())
                {
                    byte[] buffer = new byte[BUFF_SIZE];
                    int byteRead = BUFF_SIZE;
                    while (byteRead == BUFF_SIZE)
                    {
                        byteRead = fs.Read(buffer, 0, buffer.Length);
                        ftpstream.Write(buffer, 0, byteRead);
                    }
                }
            }
            result = "ftp://" + ftpHost + ftpfilepath.Replace(Path.GetFileName(ftpfilepath), string.Empty);
            return result;
        }
    }
}
